import HttpClient from '../commons/http-client';
import {updateRoleList} from '../reducers/role-list';
import {updateRoleDetail} from '../reducers/role-detail';

export function loadRoleList(payload) {
  return async dispatch => {
    const info = {
      page: payload.page,
      page_size: 10,
      expand: 'perms',
    };
    const url = `/admin/role?${HttpClient.encodeParams(info)}`;
    const roleListRep = await HttpClient.get(url);
    dispatch(updateRoleList(roleListRep.data.data));
  };
}

export function disableRole(payload) {
  return async (dispatch, getState) => {
    const {roleList} = getState();
    const roleRep = await HttpClient.put(`/admin/role/${payload.id}/edit`, {
      role: payload,
    });
    roleList.results = roleList.results.map(val =>
      val.id === roleRep.data.data.id ? roleRep.data.data : val,
    );
    dispatch(updateRoleList(roleList));
  };
}

export function newRole(payload) {
  return async dispatch => {
    if (!payload.targetKeys.includes('master_manage')) {
      payload.targetKeys.push('master_manage');
    }
    const roleInfo = {
      role: {
        name: payload.roleName,
        desc: payload.roleDesc,
      },

      perms: payload.targetKeys.map(item => ({
        menu: item,
        get: true,
        post: true,
        put: true,
        delete: true,
      })),
    };
    await HttpClient.post('/admin/role/new', roleInfo);
    const info = {
      page: 1,
      page_size: 10,
      expand: 'perms',
    };
    const url = `/admin/role?${HttpClient.encodeParams(info)}`;
    const roleListRep = await HttpClient.get(url);
    dispatch(updateRoleList(roleListRep.data.data));
  };
}

export function delRole(payload) {
  return async dispatch => {
    await HttpClient.delete(`/admin/role/${payload.id}`);
    const info = {
      page: 1,
      page_size: 10,
      expand: 'perms',
    };
    const url = `/admin/role?${HttpClient.encodeParams(info)}`;
    const roleListRep = await HttpClient.get(url);
    dispatch(updateRoleList(roleListRep.data.data));
  };
}

export function loadRoleDetail(payload) {
  return async dispatch => {
    dispatch(updateRoleDetail(payload));
  };
}

export function updateRole(payload) {
  return async dispatch => {
    if (!payload.targetKeys.includes('master_manage')) {
      payload.targetKeys.push('master_manage');
    }
    const roleInfo = {
      role: {
        desc: payload.roleDesc,
      },
      perms: payload.targetKeys.map(item => ({
        menu: item,
        get: true,
        post: true,
        put: true,
        delete: true,
      })),
    };
    const roleRep = await HttpClient.put(
      `/admin/role/${payload.id}/edit`,
      roleInfo,
    );
    dispatch(updateRoleDetail(roleRep.data.data));
  };
}
